<script lang="ts" setup>
import { useWebSocket } from '@vueuse/core';
import storage from 'store';
import { ElNotification } from 'element-plus';
import logo from '@/assets/logo/audaque.png';
import avatar from '@/assets/avatar/defaultAvatar.png';
import { useUserStore } from '@/stores/user';
import { useHeaderStore } from '@/stores/header';
import MenuTree from '@/views/main/menuTree.vue';
import Menu from '@/model/common/menu';
import { getCurrentIndexPath } from '@/libs/utils';
import router from '@/router';
import { MessagePayload } from '@/model';
import Message from '@/views/main/message.vue';

const headerStore = useHeaderStore();
const userStore = useUserStore();

const logoImg = ref<string>(logo);
const defaultAvatar = ref<string>(avatar);
const username = ref('');
const menuList = reactive<Array<Menu>>([]);
const currentIndexPath = ref<Array<string>>([]);

const msgTotal = ref<number>(0);
const visible = ref<boolean>(false);

const { title } = storeToRefs(headerStore);

// websocket
const token = storage.get('ACCESS_TOKEN');
// 做了代理，这里直接写localhost就行
const { data } = useWebSocket<MessagePayload>(
  `ws://localhost:8080/ws/message?Authorization=${token}`,
  {
    heartbeat: {
      message: 'websocket心跳检测',
      interval: 5000,
      pongTimeout: 3000,
    },
    autoReconnect: {
      retries: 3,
      delay: 1000,
      onFailed() {
        ElNotification.warning({
          title: '警告',
          message: 'WebSocket尝试重连3次失败',
        });
      },
    },
  },
);

// 监听消息数量的变化
watch(
  () => data.value,
  () => {
    if (data.value) {
      const str = `${data.value}`;
      const parse = JSON.parse(str);
      msgTotal.value = Number(parse.content);
    }
  },
);

/**
 * 关闭弹窗时调用
 */
const onCloseDialog = () => {
  visible.value = false;
};

/**
 * 点击消息按钮，弹出消息框
 */
const onMessage = () => {
  visible.value = true;
};

// 退出登录
const handleCommand = (command: string | number | object) => {
  if (command === 'logout') {
    userStore.logout().then(() => {
      userStore.$patch((state: any) => {
        state.isLogin = false;
      });
    });
  }
};

/**
 * 切换菜单时调用
 * @param index 选中菜单项的 index，也是路由
 * @param indexPath 选中菜单项的 index path，这里会得到一个数组，相当于菜单展开的路径
 */
const onSelectMenu = (index: string, indexPath: Array<string>) => {
  currentIndexPath.value = indexPath;
};

onMounted(() => {
  userStore.getMenu().then((menus: Array<Menu>) => {
    if (!menus.length) {
      return;
    }
    menus.forEach((item: Menu) => {
      menuList.push(item);
    });
    userStore.getDefaultPath().then((paths: Array<string>) => {
      if (paths.length) {
        currentIndexPath.value = paths;
      } else {
        const defaultPath = getCurrentIndexPath(menuList);
        const { path } = router.currentRoute.value;
        if (path === '/main' && defaultPath.length - 1 > 0) {
          // 当路由为/main时，所有菜单都是收起的，这里设置默认打开第一个菜单。并且跳转到第一个菜单的页面
          router.push({ path: defaultPath[defaultPath.length - 1] });
        }
        currentIndexPath.value = defaultPath;
      }
    });
  });
  userStore.getName().then((name: string) => {
    // 用户真实姓名
    if (name) {
      username.value = name;
    } else {
      // 使用登录名
      userStore.getUsername().then((name: string) => {
        username.value = name;
      });
    }
  });
});
</script>

<template>
  <div class="main-container">
    <el-container>
      <el-aside width="200px">
        <div class="main-logo">
          <el-image :src="logoImg" fit="scale-down"></el-image>
          <span>礼上来往</span>
        </div>
        <el-menu
          :default-active="$route.path"
          :default-openeds="currentIndexPath"
          class="main-menu"
          router
          @select="onSelectMenu"
        >
          <menu-tree :menu-list="menuList" :current-index-path="currentIndexPath" />
        </el-menu>
      </el-aside>
      <el-container>
        <el-header class="main-header">
          <div class="title">
            {{ title }}
          </div>
          <el-badge :value="msgTotal === 0 ? '' : msgTotal" :max="99" class="btn-msg">
            <el-icon size="24" color="#c1c4cc" @click="onMessage">
              <i-ep-bell />
            </el-icon>
          </el-badge>
          <div class="main-user">
            <el-avatar class="main-user-avatar" :src="defaultAvatar"></el-avatar>
            <el-dropdown :hide-on-click="false" @command="handleCommand">
              <span>
                {{ username }}
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-header>
        <el-main>
          <router-view />
        </el-main>
      </el-container>
    </el-container>
    <message :visible="visible" @close-dialog="onCloseDialog" />
  </div>
</template>

<style scoped lang="scss">
.main-container {
  height: 100vh;
  width: 100%;
  overflow: hidden;

  .el-aside {
    height: 100vh;
    width: 260px;
    overflow: hidden;

    .main-logo {
      height: 80px;
      width: 100%;
      background-color: #ffffff;
      margin: 0 0 1px 20px;
      text-align: left;

      .el-image {
        height: 40px;
        margin: 20px 0;
      }

      span {
        position: absolute;
        line-height: 80px;
        margin: 5px;
        color: #595757;
        font-size: 18px;
        font-weight: bold;
      }
    }

    .main-menu {
      overflow: hidden;
      height: 100%;
      border-right: solid 1px #f1f3f5;
    }
  }

  .el-header {
    background-color: #ffffff;
    height: 80px;
    padding: 1px 0 0 2px;

    .title {
      height: 40px;
      float: left;
      color: #595757;
      font-size: 28px;
      font-weight: bold;
      margin: 30px 0 0 30px;
    }

    .btn-msg {
      position: absolute;
      right: 240px;
      top: 28px;
      color: #9ca3af;
    }

    .main-user {
      height: 60px;
      width: 160px;
      position: absolute;
      top: 10px;
      right: 30px;
      display: flex;
      align-items: center;

      .main-user-avatar {
        width: 58px;
        height: 58px;
        border: 1px solid #c0c4cc;

        :hover {
          border-radius: 29px;
          box-shadow: 0 0 0 1px #c0c4cc inset;
        }
      }

      ::v-deep(.el-tooltip__trigger) {
        width: 80px;
        max-width: 140px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        font-size: 18px;
        margin-left: 14px;
      }
    }
  }

  .el-main {
    overflow: hidden;
    padding: 0;
    background-color: #fafafa;
  }
}
</style>
